﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Threading.Tasks;
using PARK.CardAcct.Interfaces;
using PARK.CardAcct.Entitys.Dto.employee;
using PARK.System.Interfaces.Permission;
using PARK.CardAcct.Entitys;
using PARK.System.Interfaces.Common;
using PARK.System.Interfaces.System;
using PARK.CardAcct.Entitys.Dto.Cardtypes;
using System.Text;
using System.Collections.Generic;

namespace PARK.CardAcct.Employee
{
    /// <summary>
    /// 服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Card", Name = "Cardtypes", Order = 200)]
    [Route("api/card/[controller]")]
    public class CardtypesService : ICardtypesService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<CardtypesEntity> _baseCardtypesRepository;
        private readonly IBillRullService _billRuleService;
        private readonly IFileService _fileService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly IOrganizeService _organizeService; // 机构表仓储

        /// <summary>
        /// 初始化一个<see cref="CardtypesService"/>类型的新实例
        /// </summary>
        public CardtypesService(
            ISqlSugarRepository<CardtypesEntity> baseCardtypesRepository,
            IBillRullService billRuleService,
            IFileService fileService,
            IUserManager userManager,
            IOrganizeService organizeService)
        {
            _baseCardtypesRepository = baseCardtypesRepository;
            _billRuleService = billRuleService;
            _fileService = fileService;
            _db = _baseCardtypesRepository.Context;
            _userManager = userManager;
            _organizeService = organizeService;
        }

        #region Get
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<CardtypesInfoOutput>();            
            return output;
        }        
        /// <summary>
		/// 获取管理列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] CardtypesListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "CardTypeCode" : input.sidx; 
                var data = await _db.Queryable<CardtypesEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .Where(u => u.IsDeleted == 0)                    
                    //关键字查询
                    .WhereIF(!input.keyword.IsNullOrEmpty(), u => u.CardTypeCode.Contains(input.keyword) || u.CardTypeName.Contains(input.keyword))                    
                    .Select(it => new CardtypesListOutput
                    {
                        Id = it.Id,
                        CardTypeCode = it.CardTypeCode,
                        CardTypeName = it.CardTypeName,
                        EnabledMark = it.EnabledMark,                                            
                        Description = it.Description,
                        CreatorTime = it.CreatorTime,
                        CreatorUserId = it.CreatorUserId,
                        CreatorUserName = it.CreatorUserName,
                        CompanyId = it.CompanyId,
                        CompanyName = it.CompanyName
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<CardtypesListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }        
        #endregion

        #region Post
        /// <summary>
        /// 新建管理
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] CardtypesCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var chkCardtype = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.CardTypeCode == input.cardTypeCode && p.IsDeleted == 0 && p.CompanyId == userInfo.companyId);
                if (chkCardtype != null)
                {
                    throw PARKException.Bah("所填 [卡类型编号] 已占用！");
                }
                chkCardtype = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.CardTypeName == input.cardTypeName && p.IsDeleted == 0 && p.CompanyId == userInfo.companyId);
                if (chkCardtype != null)
                {
                    throw PARKException.Bah("所填 [卡类型名称] 已占用！");
                }
                var entity = input.Adapt<CardtypesEntity>();
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;                
                entity.Create();
                var isOk = await _db.Insertable(entity).ExecuteCommandAsync();
                if (!(isOk > 0))
                {
                    throw PARKException.Oh(ErrorCode.COM1000);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 更新管理
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] CardtypesUpInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var chkCardtype = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.CardTypeCode == input.cardTypeCode && p.IsDeleted == 0 && p.CompanyId == userInfo.companyId && p.Id!=input.id);
                if (chkCardtype != null)
                {
                    throw PARKException.Bah("所填 [卡类型编号] 已占用！");
                }
                chkCardtype = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.CardTypeName == input.cardTypeName && p.IsDeleted == 0 && p.CompanyId == userInfo.companyId && p.Id != input.id);
                if (chkCardtype != null)
                {
                    throw PARKException.Bah("所填 [卡类型名称] 已占用！");
                }
                var entity = input.Adapt<CardtypesEntity>();
                entity.LastModify(id);
                //更新
                var Paras = new List<SugarParameter>();
                StringBuilder dbSql = new StringBuilder();
                dbSql.Append("update base_cardtypes set ");
                dbSql.AppendFormat("CardTypeCode='{0}',CardTypeName='{1}',EnabledMark={2},Description='{3}',", entity.CardTypeCode, entity.CardTypeName, entity.EnabledMark, entity.Description);
                dbSql.AppendFormat("LastModifyUserId='{0}',LastModifyUserName='{1}',LastModifyTime='{2}'", entity.LastModifyUserId, entity.LastModifyUserName, Convert.ToDateTime(entity.LastModifyTime).ToString("yyyy-MM-dd HH:mm:ss"));
                dbSql.AppendFormat(" where Id='{0}'", id);
                var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.Id == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                try
                {
                    entity.Delete(id);
                    //更新
                    var Paras = new List<SugarParameter>();
                    StringBuilder dbSql = new StringBuilder();
                    dbSql.Append("update base_cardtypes set ");                   
                    dbSql.AppendFormat("IsDeleted=1,DeleteUserId='{0}',DeleteUserName='{1}',DeleteTime='{2}'", entity.DeleteUserId, entity.DeleteUserName,Convert.ToDateTime(entity.DeleteTime).ToString("yyyy-MM-dd HH:mm:ss"));
                    dbSql.AppendFormat(" where Id='{0}'", id);
                    var isOk = await _db.Ado.ExecuteCommandAsync(dbSql.ToString(), Paras);              
                }
                catch (Exception ex)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
            {
                throw PARKException.Bah("您的权限无法操作!");
            }
        }
        #endregion

        /// <summary>
        /// 获取下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("Selector/{id}")]
        public async Task<dynamic> GetSelector(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var data= await _db.Queryable<CardtypesEntity>().Where(t => t.IsDeleted == 0 && t.EnabledMark == 1 && t.CompanyId == userInfo.companyId).Select(it => new CardtypesSelectorOutput
                {
                    CardTypeId = it.Id,
                    CardTypeName = it.CardTypeName                   
                }).ToListAsync();

                return new { list = data };
            }
            else
                return null;
        }
        /// <summary>
		/// 获取卡类型列表
		/// </summary>
		/// <returns></returns>
        [HttpGet("GetTransferList")]
        public async Task<dynamic> GetTransferList()
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var data = await _db.Queryable<CardtypesEntity>()
                .Where(p => p.CompanyId.Equals(userInfo.companyId) && p.IsDeleted == 0 && p.EnabledMark == 1)//权限
                 .Select(it => new CardtypesSelectorOutput
                 {
                     CardTypeId = it.Id,
                     CardTypeName = it.CardTypeName
                 }).MergeTable().ToListAsync();
                return data;
            }
            else
            {
                return null;
            }
        }
    }
}
   